package com.devops.admin.util;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Set;

/**
 * ClassName TailLogUtil
 * Description TODO
 * Author hepingguo
 * Date 2022/4/27 11:37
 * Version 1.0
 **/
@Slf4j
public class PodStatusUtil extends Thread{

    private final BufferedReader reader;

    private Session session;

    private final Set<Session> openSessions;


    public PodStatusUtil(InputStream logs, Session session) {
        this.reader = new BufferedReader(new InputStreamReader(logs));
        this.session = session;
        this.openSessions = session.getOpenSessions();
    }

    @Override
    public void run() {
        try {
            sendStatus();
        } catch (IOException e) {
            System.out.println("thead raed file error:" + e);
        }
    }

    private void sendStatus() throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            // 将实时日志通过WebSocket发送给客户端
            if (!session.isOpen()){
                if (CollectionUtil.isNotEmpty(openSessions)) {
                    this.session = openSessions.stream().findFirst().orElse(this.session);
                }
            }
            this.session.getBasicRemote().sendText(line);
        }
    }

}
